<?php


namespace app\api\controller\Video;


use app\api\controller\AppController;
use app\api\model\User\UserWatchLogModel;
use app\api\model\Video\VideoCommentModel;
use app\api\model\Video\VideoCourseRelationModel;
use app\api\model\Video\VideoGoodsRelationModel;
use app\api\model\Video\VideoCateModel;
use app\api\model\Video\VideoChapterModel;
use app\api\model\Video\VideoLikeModel;
use app\api\model\Video\VideoModel;
use app\Request;
use app\Utils\ImageUtil;
use app\Utils\Util;

class Video extends AppController
{
    /**
     * @api {get} /get_video_cate_more 视频分类
     * @apiGroup 视频
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getVideoCateMore(Request $request)
    {
        $list = [
            [
                'id'=>0,
                'cate_name'=>"推荐"
            ]
        ];
        $data = VideoCateModel::getVideoCateWhereMore([['is_show','=',1]]);
        foreach ($data as $item){
            $arr['id'] = $item['id'];
            $arr['cate_name'] = $item['cate_name'];
            array_push($list,$arr);
        }
        return Util::returnJson(self::CODE_SUCCESS,$list);
    }

    /**
     * @api {get} /get_video_list 视频列表
     * @apiGroup 视频
     * @apiParam {int} page 页码
     * @apiParam {int} limit 数据条数
     * @apiParam {string} video_title 搜索视频名字
     * @apiParam {int} cate_id 视频分类ID ID为0为推荐视频
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getVideoList(Request $request)
    {
        $param = $request->param();
        $where = [
            ['v.is_show','=',1]
        ];
        $page = !empty($param['page']) ? $param['page'] : 1;
        $limit = !empty($param['limit']) ? $param['limit'] : 10;
        $video_title = !empty($param['video_title']) ? $param['video_title'] : "";
        $cate_id = isset($param['cate_id']) ? $param['cate_id'] : "";
        if(!empty($video_title)) {
            array_push($where, ['v.video_title', 'like', '%' . $video_title . '%']);
        }
        if(isset($cate_id)){
            if($cate_id == 0){
                array_push($where, ['v.is_recommend', '=', 1]);
            }else{
                array_push($where, ['vcr.cate_id', '=', $cate_id]);
            }
        }
        $list = VideoModel::getVideoListWhere($page, $limit, $where);
        $count = VideoModel::getVideoCountWhere($where);
        foreach ($list as &$item){
            $item['label'] = !empty($item['label']) ? json_decode($item['label'],true) : [];
            $item['img'] = ImageUtil::i()->replaceUrl($item['img']);
            $images = !empty($item['slider_img']) ? json_decode($item['slider_img'],true) : [];
            foreach ($images as &$image){
                $image = ImageUtil::i()->replaceUrl($image);
            }
            $item['slider_img'] = $images;
            $item['details'] = !empty($item['details']) ? htmlspecialchars_decode($item['details']) : "";
        }
        return Util::returnPageJson(self::CODE_SUCCESS, $count, $list, "");
    }

    /**
     * @api {get} /get_video_info 视频详情
     * @apiGroup 视频
     * @apiParam {string} token Token
     * @apiParam {int} id 视频ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getVideoInfo(Request $request)
    {
        $param = $request->param();
        $video = VideoModel::getVideoWhere([['id','=',$param['id']]]);
        if(!empty($video)){
            $video['label'] = !empty($video['label']) ? json_decode($video['label'],true) : [];
            $video['img'] = ImageUtil::i()->replaceUrl($video['img']);
            $images = !empty($video['slider_img']) ? json_decode($video['slider_img'],true) : [];
            foreach ($images as &$image){
                $image = ImageUtil::i()->replaceUrl($image);
            }
            $video['slider_img'] = $images;
            $video['details'] = !empty($video['details']) ? htmlspecialchars_decode($video['details']) : "";
            //章节列表
            $chapters = VideoChapterModel::getVideoChapterWhereMore(['video_id'=>$video['id']]);
            if(!empty($chapters)){
                foreach ($chapters as &$item){
                    $item['lock'] = 0;
                    if($item['is_free']){
                        if(empty($user['is_level_type'])){
                            if(empty($user['level_id'])){
                                $item['lock'] = 1;
                            }else if(strtotime($user['end_time']) < time()){
                                $item['lock'] = 1;
                            }
                        }
                    }
                }
                unset($item);
                $video['chapters'] = $chapters;
            }else{
                $video['chapters'] = [];
            }
            //相关商品
            $goods = VideoGoodsRelationModel::getVideoGoodsRelationWhereMore(['vgr.video_id'=>$video['id']],'g.id,g.img,g.slider_img,g.good_name,g.price,g.vip_price,g.cost_price,g.stock,g.sales');
            if(!empty($goods)){
                foreach ($goods as &$good){
                    $good['img'] = ImageUtil::i()->replaceUrl($good['img']);
                    $images = !empty($good['slider_img']) ? json_decode($good['slider_img'],true) : [];
                    foreach ($images as &$image){
                        $image = ImageUtil::i()->replaceUrl($image);
                    }
                    $good['slider_img'] = $images;
                }
                $video['goods'] = $goods;
            }else{
                $video['goods'] = [];
            }
            //相关课程
            $courses = VideoCourseRelationModel::getVideoCourseRelationWhereMore(['vcr.video_id'=>$video['id']],'c.id,c.img,c.slider_img,c.title,c.price,c.vip_price,c.cost_price,cc.cate_name,sa.area_name');
            if(!empty($courses)){
                foreach ($courses as &$course){
                    $course['img'] = ImageUtil::i()->replaceUrl($course['img']);
                    $images = !empty($course['slider_img']) ? json_decode($course['slider_img'],true) : [];
                    foreach ($images as &$image){
                        $image = ImageUtil::i()->replaceUrl($image);
                    }
                    $course['slider_img'] = $images;
                }
                $video['courses'] = $courses;
            }else{
                $video['courses'] = [];
            }
        }
        return Util::returnJson(self::CODE_SUCCESS, $video, "");
    }

    /**
     * @api {get} /get_video_chapter_info 视频章节详情
     * @apiGroup 视频
     * @apiParam {string} token Token
     * @apiParam {int} id 视频章节ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getVideoChapterInfo(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        if (empty($param['id'])){
            return Util::returnJson(self::CODE_ERROR, null, "参数错误");
        }
        $chapter = VideoChapterModel::getVideoChapterWhere([['id','=',$param['id']]]);
        if($chapter['is_free']){
            if(empty($user['is_level_type'])){
                if(empty($user['level_id'])){
                    return Util::returnJson(self::CODE_ERROR, null, "请购买会员");
                }else if(strtotime($user['end_time']) < time()){
                    return Util::returnJson(self::CODE_ERROR, null, "会员已过期");
                }
            }
        }
        if(!empty($chapter)){
            //相关商品
            $goods = VideoGoodsRelationModel::getVideoGoodsRelationWhereMore(['vgr.video_id'=>$chapter['video_id']],'g.id,g.img,g.slider_img,g.good_name,g.price,g.vip_price,g.cost_price,g.stock,g.sales');
            if(!empty($goods)){
                foreach ($goods as &$good){
                    $good['img'] = ImageUtil::i()->replaceUrl($good['img']);
                    $images = !empty($good['slider_img']) ? json_decode($good['slider_img'],true) : [];
                    foreach ($images as &$image){
                        $image = ImageUtil::i()->replaceUrl($image);
                    }
                    $good['slider_img'] = $images;
                }
                $video['goods'] = $goods;
            }else{
                $chapter['goods'] = [];
            }
            //相关课程
            $courses = VideoCourseRelationModel::getVideoCourseRelationWhereMore(['vcr.video_id'=>$chapter['video_id']],'c.id,c.img,c.slider_img,c.title,c.price,c.vip_price,c.cost_price,cc.cate_name,sa.area_name');
            if(!empty($courses)){
                foreach ($courses as &$course){
                    $course['img'] = ImageUtil::i()->replaceUrl($course['img']);
                    $images = !empty($course['slider_img']) ? json_decode($course['slider_img'],true) : [];
                    foreach ($images as &$image){
                        $image = ImageUtil::i()->replaceUrl($image);
                    }
                    $course['slider_img'] = $images;
                }
                $video['courses'] = $courses;
            }else{
                $chapter['courses'] = [];
            }

            //用户是否点赞
            $is_like = 0;
            $like = VideoLikeModel::getVideoLikeCountWhere([['uid','=',$this->user['id']],['chapter_id','=',$param['id']]]);
            if(!empty($like)){
                $is_like = 1;
            }
            $chapter['is_like'] = $is_like;
            //点赞数
            $chapter['like_count'] = VideoLikeModel::getVideoLikeCountWhere([['chapter_id','=',$param['id'],['status','=',1]]]);
            //评论数
            $chapter['comment_count'] = VideoCommentModel::getVideoCommentCountWhere([['vc.chapter_id','=',$chapter['id']]]);

        }

        //添加更新观看记录
        $where = [
            ['uid','=',$user['id']],
            ['video_id','=',$chapter['video_id']],
            ['add_time','>',date("Y-m-d 00:00:00",time())]
        ];
        $watch_log = UserWatchLogModel::getUserWatchLogWhere($where);
        if(!empty($watch_log)){
            $save = [
                'up_time' => date("Y-m-d H:i:s",time())
            ];
            UserWatchLogModel::updateUserWatchLog([['id','=',$watch_log['id']]],$save);
        }else{
            $data = [
                'uid'      => $user['id'],
                'video_id' => $chapter['video_id'],
                'up_time'  => date("Y-m-d H:i:s",time()),
                'add_time' => date("Y-m-d H:i:s",time())
            ];
            UserWatchLogModel::addUserWatchLog($data);
        }
        return Util::returnJson(self::CODE_SUCCESS, $chapter, "");
    }

    /**
     * @api {post} /get_video_like 视频点赞/取消
     * @apiGroup 视频
     * @apiParam {string} token Token
     * @apiParam {int} video_id 视频ID
     * @apiParam {int} chapter_id 章节ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getVideoLike(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        $video_id = !empty($param['video_id']) ? $param['video_id'] : 0;
        $chapter_id = !empty($param['chapter_id']) ? $param['chapter_id'] : 0;
        if(empty($video_id) && empty($chapter_id)){
           return Util::returnJson(self::CODE_ERROR,null,"参数错误");
        }

        $like = VideoLikeModel::getVideoLikeWhere([['uid','=',$user['id']],['video_id','=',$video_id],['chapter_id','=',$chapter_id]]);
        if(!empty($like)){
            //修改
            $data = [
                'status'    => !empty($like['status']) ? 0 : 1,
            ];
            VideoLikeModel::updateVideoLikeWhere([['uid','=',$user['id']],['video_id','=',$video_id],['chapter_id','=',$chapter_id]],$data);
        }else{
            //添加
            $data = [
                'uid'       => $user['id'],
                'status'    => 1,
                'video_id' => $video_id,
                'chapter_id' => $chapter_id,
                'add_time'  => date("Y-m-d H:i:s",time())
            ];
            VideoLikeModel::addVideoLike($data);
        }
        $like['like_count'] = VideoLikeModel::getVideoLikeCountWhere([['chapter_id','=',$chapter_id],['status','=',1]]);
        if(!empty($data['status'])){
            $like['is_like'] = 1;
            return Util::returnJson(self::CODE_SUCCESS,$like,"点赞成功");
        }else{
            $like['is_like'] = 0;
            return Util::returnJson(self::CODE_SUCCESS,$like,"取消成功");
        }
    }

    /**
     * @api {post} /get_video_comment 视频评论
     * @apiGroup 视频
     * @apiParam {string} token Token
     * @apiParam {int} video_id 视频ID
     * @apiParam {int} chapter_id 章节ID
     * @apiParam {string} content 评论内容
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getVideoComment(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        $video_id = !empty($param['video_id']) ? $param['video_id'] : 0;
        $chapter_id = !empty($param['chapter_id']) ? $param['chapter_id'] : 0;
        if(empty($video_id) && empty($chapter_id)){
            return Util::returnJson(self::CODE_ERROR,null,"参数错误");
        }
        if(empty($param['content'])){
            return Util::returnJson(self::CODE_ERROR,null,"请输入评论");
        }
        $data = [
            'uid'        => $user['id'],
            'content'    => !empty($param['content']) ? $param['content'] : "",
            'video_id'   => $video_id,
            'chapter_id' => $chapter_id,
            'add_time'   => date("Y-m-d H:i:s",time())
        ];
        $id = VideoCommentModel::addVideoComment($data);
        if($id){
            $comment = VideoCommentModel::getVideoCommentWhere([['vc.id','=',$id]],"vc.*,u.nickname,u.head_img");
            $comment['head_img'] = ImageUtil::i()->replaceUrl($comment['head_img']);
            $comment['comment_count'] = VideoCommentModel::getVideoCommentCountWhere([['vc.chapter_id','=',$chapter_id]]);
            return Util::returnJson(self::CODE_SUCCESS,$comment,"评论成功");
        }else{
            return Util::returnJson(self::CODE_ERROR,null,"评论失败");
        }
    }

    /**
     * @api {get} /get_video_comment_list 评论列表
     * @apiGroup 视频
     * @apiParam {int} page 页码
     * @apiParam {int} limit 数据条数
     * @apiParam {int} chapter_id 章节
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getVideoCommentList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $page = !empty($param['page']) ? $param['page'] : 1;
        $limit = !empty($param['limit']) ? $param['limit'] : 10;
        if(empty($param['chapter_id'])){
            return Util::returnJson(self::CODE_ERROR,null,"参数错误");
        }else{
            array_push($where,['vc.chapter_id','=',$param['chapter_id']]);
        }

        $list = VideoCommentModel::getVideoCommentListWhere($page, $limit, $where,"vc.*,u.nickname,u.head_img");
        $count = VideoCommentModel::getVideoCommentCountWhere($where);
        foreach ($list as &$item){
            $item['head_img'] = ImageUtil::i()->replaceUrl($item['head_img']);
        }
        unset($item);
        return Util::returnPageJson(self::CODE_SUCCESS, $count, $list, "");
    }

}